//urp
Shader "czs/water"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "black" {}
		_Color("Color",Color) = (1,1,1,1)
		_DepthMin("DepthMin",Range(0,1)) = 0.1
		_DepthMax("DepthMax",Range(0,1)) = 0.2
        _FoamShapeTex("FoamShapeTex",2D) = "white"{}
        _FoamRange("FoamRange",Range(0.01,3)) = 0.1
        _FoamSmoothness("FoamSmoothness",Range(0.01,3)) = 0.1
	}
	SubShader
	{
		Tags
        { 
            "RenderType"="Transparent"
            "RenderPipeline"="UniversalRenderPipeline"
        }
		LOD 100
		Pass
		{
			Name "Unlit"
            Tags
            {
                "LightMode"="UniversalForward"
            }
		}
        HLSLPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
            half3 normalOS:NORMAL;
        };
        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
            half3 normalWS:TEXCOORD1;
            half3 posWS:TEXCOORD2;


        };

        sampler2D _MainTex;
        float4 _MainTex_ST;
        half4 _MainColor;
        float4 _Color;
        float _DepthMin;
        float _DepthMax;
        sampler2D _FoamShapeTex;
        float4 _FoamShapeTex_ST;//tilling and offset
        float _FoamRange;//tilling and offset
        float _FoamSmoothness;//tilling and offset
        half4 _WaterColorShallow;
        half4 _WaterColorDeep;
        
        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = TransformObjectToHClip(v.vertex.xyz);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            o.normalWS = TransformObjectToWorldNormal(v.normalOS);
            o.posWS = TransformObjectToWorld(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _FoamShapeTex)+_Time.x;// 将uv坐标转换为纹理坐标
            return o;
        }
        half4 frag (v2f i) : SV_Target
        {
        
    float2 uvScreen = i.posCS.xy / _ScreenParams.xy;  // 屏幕空间的uv坐标    
    float depth;// 深度值
    depth = tex2D(_CameraDepthTexture, uvScreen).r;  // 从深度纹理中采样深度值
    depth = LinearEyeDepth(depth,_ZBufferParams);  // 线性化深度值
//depth *= _DepthMax; //d3d
//水的深度 = 场景中不透明物体的深度 - 水面各个片元在观察空间的z值
//i.posVS.z:Unity观察空间用右手坐标系，z是负数，离摄像机越近，越接近于0
float height =depth + i.posVS.z;//水底到水面的高度
//    return tex2D(_FoamShapeTex,uvScreen);//debugger
half foamShape = tex2D(_FoamShapeTex,uvScreen).r;
float foamRange = _FoamRange*height;// 
foamShape = pow(foamShape,_FoamSmoothness);// 抹平差异
   foamShape =  step(foamRange,foamShape );
            return foamShape;//debugger

//对纹理采样
half4 col = lerp(_WaterColorShallow,_WaterColorDeep,height);

// foam howtodo texture
            // return col;
            return foamShape + col;
        }
        ENDHLSL
    
    
    }
}